#include "httprequest.h"
#include <QJsonObject>
HttpRequest::HttpRequest(QObject *parent) : QObject(parent)
{

}
bool HttpRequest::post_request(QString Url,QMap<QString,QString> header,QByteArray& requestData,QByteArray& replyData)
{
    //执行发送请求动作
    QNetworkAccessManager manager;
    //创建请求的对象（整合url和header）
    QNetworkRequest request;
    request.setUrl(Url);
    //遍历header（因为请求了两次）
    QMapIterator<QString,QString> iter(header);
    request.setHeader(request.ContentTypeHeader, ("text/html; charset=utf-8"));
    while(iter.hasNext())
    {
        iter.next();
        request.setRawHeader(iter.key().toLatin1(),iter.value().toLatin1());//Latin1是一种编码，类似的还有utf-8
    }
    QNetworkReply *reply=manager.post(request,requestData);
    QEventLoop loop;
    connect(reply,&QNetworkReply::finished,&loop,&QEventLoop::quit);    //等待服务器返回-进入阻塞状态
    loop.exec();
    if(reply!=nullptr && reply->error()==QNetworkReply::NoError)//nullptr空指针
    {
        replyData=reply->readAll();
        return true;
    }
    else
    {
        qDebug()<<"返回失败！"<<reply;
        return false;
    }
}
